package com.mouse.remind;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;


public class AlarmBootService extends Service{
	

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		Log.d(this.getClass().getSimpleName(),"onCreate()");
		super.onCreate();		
	}

	private AlarmModel getNext(){
		Set<AlarmModel> alarmQueue = new TreeSet<AlarmModel>(new Comparator<AlarmModel>() {
			@Override
			public int compare(AlarmModel lhs, AlarmModel rhs) {
				int result = 0;
				long diff = lhs.getAlarmTime().getTimeInMillis() - rhs.getAlarmTime().getTimeInMillis();				
				if(diff>0){
					return 1;
				}else if (diff < 0){
					return -1;
				}
				return result;
			}
		});
				
		Database.init(getApplicationContext());
		List<AlarmModel> alarms = Database.getAll();
		
		for(AlarmModel alarm : alarms){
			if(alarm.getActive())
				alarmQueue.add(alarm);
		}
		if(alarmQueue.iterator().hasNext()){
			return alarmQueue.iterator().next();
		}else{
			return null;
		}
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		Database.deactivate();
		super.onDestroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(this.getClass().getSimpleName(),"onStartCommand()");
		AlarmModel alarm = getNext();
		if(null != alarm){
			Log.d(this.getClass().getSimpleName(),"alarm not null");
			alarm.schedule(getApplicationContext());
			Log.d(this.getClass().getSimpleName(),alarm.getTimeUntilNextAlarmMessage());
			
		}else{
			Log.d(this.getClass().getSimpleName(),"alarm null");
			Intent mIntent = new Intent(getApplicationContext(), AlarmAlertReceiver.class);
			mIntent.putExtra("alarm", new AlarmModel());
			
			PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mIntent,PendingIntent.FLAG_CANCEL_CURRENT);			
			AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
			
			alarmManager.cancel(pendingIntent);
		}
		return START_NOT_STICKY;
	}


}
